package com.tjnu.losca.controller;


import com.tjnu.losca.Vo.ResponseVO;
import com.tjnu.losca.pojo.User;
import com.tjnu.losca.service.ILoginService;
import com.tjnu.losca.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author losca
 * @since 2022-02-13
 */
@RestController
@RequestMapping("/Login")
public class LoginController {

    @Autowired
    ILoginService loginService;
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResponseVO Login(@RequestBody User adminUser) throws IOException {
        User user = loginService.getUserByUserName(adminUser.getUsername());
        //判断账号是否存在
        if (user == null) {
            return ResponseVO.failed("无此用户，请重新输入正确用户名");
        } else {
            //判断密码是否匹配
            if (passwordEncoder.matches(adminUser.getPwd(), user.getPwd())){
                String token = TokenUtil.token(user.getId().trim());
                return ResponseVO.success("登录成功", token);
            }else{
                //返回错误信息
                return ResponseVO.failed("密码错误");
            }
        }
    }
    @PostMapping("/updatePwdByUsername")
    public ResponseVO updatePwdByUsername(String username,String pwd) throws IOException {
        User user = loginService.getUserByUserName(username);
        boolean flag = loginService.updatePwdByUsername(user.getUsername(), passwordEncoder.encode(pwd));
        if (flag){
            return ResponseVO.success("修改成功");
        }else {
            return ResponseVO.failed("密码修改失败");
        }
    }

}
